<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2018-03-07
 * @Time: 14:10
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： AskView.php
 */
namespace app\api\model\ask;

use app\api\model\user\Users;
use app\common\model\UserCreditRecord;
use think\Db;
use think\Log;
use think\Model;

class AskView extends Model {
    protected $table = 'ask_view';
    protected $pk = 'id';

    /**
     * createView
     * 创建用户偷看问题答案记录
     *
     * @author zhengkai
     * @date 2018-03-07
     *
     * @param int $uid 用户id
     * @param int $askId 问答id
     * @return bool
     */
    public static function createView($uid, $askId)
    {
        // 如果偷看用户与提问用户相同，则不创建偷看记录，也不扣除用户的积分
        $askUser = Ask::getSingleField($askId, 'ask_user');
        if ($askUser==$uid) return true;

        Db::startTrans();
        try {
            self::create([
                'ask_id' => $askId,
                'user_id' =>  $uid,
                'credit' => Ask::$viewCredit
            ]);

            Db::commit();

            // 更新用户积分，并产生积分变动记录
            Users::consumeCredit($uid,UserCreditRecord::CHANGE_TYPE_ASK_VIEW, Ask::$viewCredit,'付费问答，答案偷看', ['ask_id' => $askId]);

            return true;
        } catch (\Exception $e) {
            Log::error('答案偷看错误信息：'.$e->getMessage());

            Db::rollback();

            return false;
        }
    }

    /**
     * checkView
     * 查询用户是否拥有查看问题答案权限
     *
     * @author zhengkai
     * @date 2018-03-07
     *
     * @param int $uid 用户id
     * @param int $askId 问答id
     * @return int
     */
    public static function checkView($uid, $askId)
    {
        $data = self::where('ask_id', $askId)
            ->where('user_id', $uid)
            ->count();

        if ($data && Ask::$viewCredit==0) {
            return 1;
        } else {
            return 0;
        }
    }
}